package com.zbiti.anvil.basic.admin.gateway.sso.sso2;

/**
 * @author Fanyc
 * @date 2025/2/10 10:56
 */

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES对称加密
 *
 * @author anvil
 * @date 2019-6-18
 */
public class AESUtil {
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    private static final String ALGORITHM = "AES";
    private static final String CHARSETNAME = "UTF-8";

    /**
     * 初始化密码
     *
     * @param encryptKey
     * @param encryptMode
     * @return
     * @throws Exception
     */
    private static Cipher initCipher(String encryptKey, int encryptMode) throws Exception {
        byte[] bytes = encryptKey.getBytes(CHARSETNAME);
        if (16 != bytes.length) {
            throw new Exception("AES密钥有误【密钥为16位大小写字母、数字、特殊字符组成】");
        }
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(encryptMode, new SecretKeySpec(bytes, ALGORITHM));
        return cipher;
    }

    /**
     * AES加密
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] encryptToBytes(String content, String encryptKey) throws Exception {
        Cipher cipher = initCipher(encryptKey, Cipher.ENCRYPT_MODE);
        return cipher.doFinal(content.getBytes(CHARSETNAME));
    }

    /**
     * 加密为Hex
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return
     */
    public static String encryptHex(String content, String encryptKey) {
        try {
            byte[] outBytes = encryptToBytes(content, encryptKey);
            return String.valueOf(Hex.encodeHex(outBytes));
        } catch (Exception e) {
            return "";
        }
    }
}
